from flask import Blueprint, jsonify, current_app, request
from sqlalchemy import asc

from models import Teacher, Department, db  # 假设 Teacher, Department 是模型，db 是数据库实例
from sqlalchemy.exc import IntegrityError

api_bp = Blueprint('teacher', __name__)


# 1. 获取教师列表
@api_bp.route('/teachers', methods=['GET'])
def get_teachers():
    try:
        page = request.args.get('page', 1, type=int)
        page_size = request.args.get('page_size', 10, type=int)
        page_size = min(max(page_size, 1), 100)

        # 关键词查询参数
        keyword = request.args.get('kw', '').strip()

        # 构建基础查询
        query = Teacher.query.join(
            Department, Teacher.department_id == Department.id, isouter=True
        ).add_columns(
            Teacher.id,
            Teacher.name,
            Teacher.teacherId,
            Teacher.gender,
            Teacher.title,
            Teacher.department_id,
            Teacher.phone,
            Department.name.label('department_name')
        ).order_by(asc(Teacher.id))

        # 添加关键词查询条件
        if keyword:
            keyword = f'%{keyword}%'  # 模糊查询
            query = query.filter(
                (Teacher.name.ilike(keyword)) |
                (Teacher.teacherId.ilike(keyword)) |
                (Teacher.title.ilike(keyword)) |
                (Department.name.ilike(keyword))  # 支持班级名称搜索
            )

        # 查询总记录数（带关键词条件）
        total_items = query.count()

        # 计算总页数
        total_pages = (total_items + page_size - 1) // page_size
        page = max(1, min(page, total_pages))  # 防止页码越界

        # 执行分页查询
        teachers = query.offset((page - 1) * page_size).limit(page_size).all()

        data = []
        for teacher in teachers:
            data.append({
                "id": teacher.id,
                "name": teacher.name,
                "teacher_id": teacher.teacherId,
                "gender": teacher.gender,
                "title": teacher.title,
                "department_id": teacher.department_id,
                "department_name": teacher.department_name,
                "phone": teacher.phone
            })

        return jsonify({
            "message": "获取教师列表成功",
            "data": data,
            "pagination": {
                "current_page": page,
                "page_size": page_size,
                "total_pages": total_pages,
                "total_items": total_items
            }
        }), 200

    except Exception as e:
        current_app.logger.error(f"获取教师列表失败: {str(e)}", exc_info=True)
        return jsonify({"message": "获取教师列表失败"}), 500


# 2. 添加教师
@api_bp.route('/teachers', methods=['POST'])
def add_teacher():
    try:
        data = request.json
        required_fields = ["name", "teacher_id", "gender", "title", "department_id", "phone"]
        for field in required_fields:
            if field not in data:
                return jsonify({"message": f"缺少必要参数: {field}"}), 400

        # 验证部门是否存在
        department = Department.query.get(data["department_id"])
        if not department:
            return jsonify({"message": "部门不存在"}), 400

        # 检查教师ID是否已存在
        existing_teacher = Teacher.query.filter_by(teacherId=data["teacher_id"]).first()
        if existing_teacher:
                return jsonify({"message": f"教师ID {data['teacher_id']} 已存在"}), 400

        new_teacher = Teacher(
            name=data["name"],
            teacherId=data["teacher_id"],
            gender=data["gender"],
            title=data["title"],
            department_id=data["department_id"],
            phone=data["phone"]
        )
        db.session.add(new_teacher)
        db.session.commit()
        return jsonify({
            "message": "教师添加成功",
            "teacher_id": new_teacher.id
        }), 201

    except IntegrityError:
        db.session.rollback()
        current_app.logger.error("数据库操作冲突")
        return jsonify({"message": "添加教师失败"}), 500
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"添加教师失败: {str(e)}", exc_info=True)
        return jsonify({"message": "添加教师失败"}), 500


# 3. 更新教师信息
@api_bp.route('/teachers/<int:teacher_id>', methods=['PUT'])
def update_teacher(teacher_id):
    try:
        data = request.json
        teacher = Teacher.query.get(teacher_id)

        if not teacher:
            return jsonify({"message": "教师记录不存在"}), 404

        # 验证部门是否存在（如果更新了部门）
        if "department_id" in data:
            department = Department.query.get(data["department_id"])
            if not department:
                return jsonify({"message": "部门不存在"}), 400

        # 检查教师ID是否被修改且新ID已存在
        if "teacher_id" in data and data["teacher_id"] != teacher.teacherId:
            existing_teacher = Teacher.query.filter(
                Teacher.teacherId == data["teacher_id"],
                Teacher.id != teacher_id
            ).first()
            if existing_teacher:
                return jsonify({"message": f"教师ID {data['teacher_id']} 已被其他教师使用"}), 400

        # 更新教师信息
        if "name" in data:
            teacher.name = data["name"]
        if "teacher_id" in data:
            teacher.teacherId = data["teacher_id"]
        if "gender" in data:
            teacher.gender = data["gender"]
        if "title" in data:
            teacher.title = data["title"]
        if "department_id" in data:
            teacher.department_id = data["department_id"]
        if "phone" in data:
            teacher.phone = data["phone"]

        db.session.commit()

        return jsonify({
            "message": "教师信息更新成功",
            "teacher_id": teacher.id
        }), 200

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"更新教师信息失败: {str(e)}", exc_info=True)
        return jsonify({"message": "更新教师信息失败"}), 500


# 4. 删除教师
@api_bp.route('/teachers/<int:teacher_id>', methods=['DELETE'])
def delete_teacher(teacher_id):
    try:
        teacher = Teacher.query.get(teacher_id)

        if not teacher:
            return jsonify({"message": "教师记录不存在"}), 404

        # 检查是否有关联课程
        if teacher.courses:
            return jsonify({"message": "该教师有关联课程，无法删除"}), 400

        db.session.delete(teacher)
        db.session.commit()

        return jsonify({"message": "教师已删除"}), 200

    except Exception as e:
        db.session.rollback()
        current_app.logger.error(f"删除教师失败: {str(e)}", exc_info=True)
        return jsonify({"message": "删除教师失败"}), 500
